//
//  ViewController.m
//  随便点
//
//  Created by qfsoft on 15-3-10.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "ViewController.h"
#import "MainTableViewCell.h"
#import "AppDelegate.h"
#import "MembersViewController.h"
#import "messageViewController.h"

#import "ShopDetailViewController.h"
#import "FirstRowCell.h"
#import "SecondRowCell.h"
#import "ThirdRowCell.h"
#import "FourthRowCell.h"
#import "MainCellTableViewCell.h"
#import "StroeMessage.h"
#import "ButtonDetailsViewController.h"
#import "SearchViewController.h"
#import "UIBarButtonItem+Badge.h"


#define kStoreURL1 @"http://www.51anys.com:8080/waimaiwang/shop/popular"   //推荐店铺接口
#define kStoreURL2 @"http://www.51anys.com:8080/waimaiwang/good/popular"    //推荐菜品接口
#define kStoreURLAd @"http://www.51anys.com:8080/waimaiwang/notice/title"    //通知接口

@interface ViewController ()
{
    NSMutableArray *storeArray;  //推荐店铺数组
    NSMutableArray *dishesArray;  //推荐菜品数组
    NSMutableArray *sarray;
    NSMutableArray *darray;
    UITableViewCell *mainCell;
    AppDelegate *app;
    NSString *cellLabel1;  //cell内容的显示
    NSString *cellLabel2;
    NSString *cellName;
    NSURL *cellImage;
    NSString *cellLabel3;
    NSString *cellLabel4;
    NSString *NoticeString;
    int str;
    UITextField *sskuang;
    NSString *nm;
    NSString *disid;
    NSString *wdxiaoxi;
    NSString *ydxiaoxi;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *navigationColor= [UIColor colorWithRed:100/255.0 green:200/255.0 blue:0/255.0 alpha:1];
    self.navigationController.navigationBar.barTintColor = navigationColor;
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.ViewC = self;
    //tableView 顶端不出现空白
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    //隐藏tableview分割线
    self.MainTableView.separatorStyle=NO;
    //导航栏添加图片
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 50.0f, 50.0f)];//初始化图片视图控件
    imageView.contentMode = UIViewContentModeScaleAspectFit;//设置内容样式,通过保持长宽比缩放内容适应视图的大小,任何剩余的区域的视图的界限是透明的。
    UIImage *image = [UIImage imageNamed:@"logo_small.png"];//初始化图像视图
    [imageView setImage:image];
    self.navigationItem.titleView = imageView;//设置导航栏的titleView为imageView
    
    sarray=[NSMutableArray array];
    dishesArray=[NSMutableArray array];
    darray=[NSMutableArray array];
    storeArray=[NSMutableArray array];
    [self setUpNotes];

    //显示通知标题
    [self setUpNotice];
    
    
    UIImage *imageitem = [UIImage imageNamed:@"xiaoxi"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0,0,imageitem.size.width,imageitem.size.height);
    [button setBackgroundImage:imageitem forState:UIControlStateNormal];
    [button addTarget:self action:@selector(message:) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem.badgeBGColor = [UIColor redColor];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)viewWillAppear:(BOOL)animated{
        if (app._id == nil||[app._id isEqualToString:@""]) {
        }else{
    [self wdxx];
        }
}
-(void)wdxx{
    NSString *xx = @"http://www.51anys.com:8080/waimaiwang/user/unread/";
    NSString *xx1 = [NSString stringWithFormat:@"%@%@",xx,app._id];
    _url=[NSURL URLWithString:xx1];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        wdxiaoxi = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:wdxiaoxi waitUntilDone:YES];
        self.navigationItem.rightBarButtonItem.badgeValue = wdxiaoxi;
    }];
}
-(void)load{
    self.MainTableView.dataSource = nil;
    if (str == 0) {
        [storeArray removeAllObjects];
        [self setUpNotes];
    }else{
        [dishesArray removeAllObjects];
        [self setUpNotes1];
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //返回cell的行数，上面内容占4个
    return storeArray.count + 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 40;
    }
    if (indexPath.row==1) {
        return 100;
    }
    if (indexPath.row==2) {
        return 140;
    }
    
    if (indexPath.row==3) {
        return 30;
    }
    
    else
        return 90;
}
-(void)buttonpress1{
    if ([sskuang.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入关键字" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        app.guanjianzi = sskuang.text;
        SearchViewController *viewController2=[[SearchViewController alloc]initWithNibName:@"SearchViewController" bundle:nil];
        
        [self.navigationController pushViewController:viewController2 animated:YES];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    // 1. 第一行：搜索框
    if (indexPath.row == 0) {
        
        UINib *nib = [UINib nibWithNibName:@"FirstRowCell" bundle:nil];
        [self.MainTableView registerNib:nib forCellReuseIdentifier:@"cell1"];
        
        
        static NSString *cellIdentifier=@"cell1";
        FirstRowCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        sskuang = cell.ss;
        cell.dj.userInteractionEnabled=YES;
        UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonpress1)];
        [cell.dj addGestureRecognizer:click];
        
        return cell;
        
        
    }
    
    // 2. 第二行：广告界面
    if (indexPath.row == 1) {
        
        UINib *nib = [UINib nibWithNibName:@"SecondRowCell" bundle:nil];
        [self.MainTableView registerNib:nib forCellReuseIdentifier:@"cell2"];
        
        
        static NSString *cellIdentifier=@"cell2";
        SecondRowCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        
        return cell;
        
    }
    
    //3. 第三行：文字滚动
    if (indexPath.row == 2) {
        
        UINib *nib = [UINib nibWithNibName:@"ThirdRowCell" bundle:nil];
        [self.MainTableView registerNib:nib forCellReuseIdentifier:@"cell3"];
        
        
        static NSString *cellIdentifier=@"cell3";
        ThirdRowCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        
        cell.LabelScroll.text=NoticeString;
        CGRect frame = cell.LabelScroll.frame;
        UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:10.0f];
        CGSize dims=[cell.LabelScroll.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
        frame.origin.x=dims.width >320 ? dims.width:320;
        [cell.LabelScroll setFrame:CGRectMake(frame.origin.x, frame.origin.y, dims.width, dims.height)];
        [UIView beginAnimations:@"testAnimation" context:NULL];
        [UIView setAnimationDuration:10.0f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationRepeatAutoreverses:NO];
        [UIView setAnimationRepeatCount:999999];
        
        frame=cell.LabelScroll.frame;
        frame.origin.x= -dims.width;
        cell.LabelScroll.frame=frame;
        [UIView commitAnimations];
        
        
        //4. 第四行： 文字显示
        cell.Label1.text=@"接单时间：09:00-19:00  配送时间：09:30-19:30";
        cell.Label1.font=[UIFont systemFontOfSize:12];
        cell.Label1.textColor=[UIColor whiteColor];
        cell.Label1.backgroundColor=[UIColor grayColor];
        cell.Label2.text=@"订餐热线：400-8282-177    0512-5820158";
        cell.Label2.font=[UIFont systemFontOfSize:12];
        cell.Label2.textColor=[UIColor whiteColor];
        cell.Label2.backgroundColor=[UIColor grayColor];
        
        //5. 第五行：“随便”分类的四个button
        [cell.Button1 addTarget:self action:@selector(toButton1) forControlEvents:UIControlEventTouchUpInside];
        [cell.Button2 addTarget:self action:@selector(toButton2) forControlEvents:UIControlEventTouchUpInside];
        [cell.Button3 addTarget:self action:@selector(toButton3) forControlEvents:UIControlEventTouchUpInside];
        [cell.Button4 addTarget:self action:@selector(toButton4) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        return cell;
        
    }
    
    
    //6. 第六行：选择控制器  “推荐店铺” “推荐菜品”
    
    if (indexPath.row == 3) {
        
        UINib *nib = [UINib nibWithNibName:@"FourthRowCell" bundle:nil];
        [self.MainTableView registerNib:nib forCellReuseIdentifier:@"cell4"];
        static NSString *cellIdentifier=@"cell4";
        FourthRowCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        _segmentedControl=cell.SegmentedControl;
        
        [ cell.SegmentedControl addTarget: self action: @selector(segmentAction:)forControlEvents: UIControlEventValueChanged];
        
        return cell;
    }
    
    //7. 第七行之后： 店铺信息
    
    else {
        if (str == 0) {
            UINib *nib=[UINib nibWithNibName:@"MainCellTableViewCell" bundle:nil];
            [_MainTableView registerNib:nib forCellReuseIdentifier:@"maincell"];
            
            static NSString *cellIdentifier=@"maincell";
            MainCellTableViewCell *cell=[_MainTableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            StroeMessage *st=storeArray[indexPath.row - 4];
            
            cell.Label1.text=@"销量：";
            cell.Label2.text=@"评价：";
            cell.Name.text = [NSString stringWithFormat:@"%@",st.StoreName];
            cell.pjLabel.text=[NSString stringWithFormat:@"%@",st.SalesNumber];
            cell.xlLabel.text=[NSString stringWithFormat:@"%@",st.StoreEvaluation];
            
            NSString *haha=@"http://www.51anys.com:8080/waimaiwang/resources/";
            NSString *hehe=[NSString stringWithFormat:@"%@",st.Image];
            NSString *string=[NSString stringWithFormat:@"%@%@",haha,hehe];
            NSURL *url=[NSURL URLWithString:string];
            cell.Image.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            
            return cell;
            
        }else{
            UINib *nib=[UINib nibWithNibName:@"MainCell" bundle:nil];
            [_MainTableView registerNib:nib forCellReuseIdentifier:@"maincell"];
            
            static NSString *cellIdentifier=@"maincell";
            MainCellTableViewCell *cell=[_MainTableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            StroeMessage *st=dishesArray[indexPath.row - 4];
            
            cell.Label1.text=@"单价：";
            cell.Label2.text=@"总量：";
            cell.Name.text = [NSString stringWithFormat:@"%@",st.dishesName];
            cell.pjLabel.text=[NSString stringWithFormat:@"%@",st.dishesPrice];
            cell.xlLabel.text=[NSString stringWithFormat:@"%@",st.dishesCount];
            nm = [NSString stringWithFormat:@"%@",st.disshopname];
            disid = [NSString stringWithFormat:@"%@",st.disshopid];
            
            NSString *haha=@"http://www.51anys.com:8080/waimaiwang/resources/";
            NSString *hehe=[NSString stringWithFormat:@"%@",st.dishesImage];
            NSString *string=[NSString stringWithFormat:@"%@%@",haha,hehe];
            NSURL *url=[NSURL URLWithString:string];
            cell.Image.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            
            
            return cell;
        }
        
    }
}

#pragma mark - 选择控制器的点击事件
-(void)segmentAction:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    switch (Index) {
        case 0:
            str= 0;
            [self load];
            break;
        case 1:
            str = 1;
            [self load];
            break;
        default:
            break;
    }
}

#pragma mark - cell的点击跳转

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row >3) {
        
        StroeMessage *store=storeArray[indexPath.row - 4];
        
        //店铺ID和店铺下的各类型传到下一个页面去
        if (str == 0) {
            app.ShopName=[NSString stringWithFormat:@"%@",store.StoreName];
            app.spid = [NSString stringWithFormat:@"%@",store.StoreId];
        }else{
            app.ShopName = [NSString stringWithFormat:@"%@",nm];
            app.spid = [NSString stringWithFormat:@"%@",disid];
        }
        app.splx = [NSString stringWithFormat:@"%@",store.StoreState];
        
        
        //跳转的页面
        ShopDetailViewController *details=[self.storyboard instantiateViewControllerWithIdentifier:@"DetailsVC"];
        [self.navigationController pushViewController:details animated:YES];
        
    }
}

#pragma mark - scrollview的响应事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // scrollView的contentOffset是最重要的属性,点,x,y记录的是滚动的距离,相对的是scrollView的可视界面的左上角的距离
    CGPoint offset = scrollView.contentOffset;
    
    int curPageNo = offset.x / scrollView.bounds.size.width;
    _pageControl.currentPage = curPageNo ;
    
}

#pragma mark - 推荐店铺下的请求数据

-(void)setUpNotes{
    
    _url=[NSURL URLWithString:kStoreURL1];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        sarray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:sarray waitUntilDone:YES];
        for(NSDictionary *obj in sarray){
            StroeMessage *store=[[StroeMessage alloc] init];
            store.Image=obj[@"image"];
            store.StoreName=obj[@"name"];
            store.StoreEvaluation=obj[@"average"];
            store.SalesNumber=obj[@"count"];
            store.StoreId=obj[@"id"];
            store.StoreState=obj[@"state"];
            [storeArray addObject:store];
        }
        self.MainTableView.dataSource = self;
        [self.MainTableView reloadData];
    }];
    
}

#pragma mark - 推荐菜品下的请求数据

-(void)setUpNotes1{
    _url=[NSURL URLWithString:kStoreURL2];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        darray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:darray waitUntilDone:YES];
        for(NSDictionary *obj in darray){
            StroeMessage *store=[[StroeMessage alloc] init];
            store.dishesImage=obj[@"image"];
            store.dishesName=obj[@"name"];
            store.dishesPrice=obj[@"price"];
            store.dishesCount=obj[@"total"];
            store.dishesId=obj[@"id"];
            store.dishesState=obj[@"state"];
            store.disshopname = obj[@"shopName"];
            store.disshopid = obj[@"shopId"];
            [dishesArray addObject:store];
        }
        self.MainTableView.dataSource = self;
        [self.MainTableView reloadData];
    }];
    
}

#pragma mark - 显示通知标题

-(void)setUpNotice{
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.51anys.com:8080/waimaiwang/notice/title"]];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        NoticeString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:NoticeString waitUntilDone:YES];
        
        
    }];

}
-(void)refreshData1:(NSArray *)sender{
    
    
}
-(void)refreshData2:(NSArray *)sender{
    
    
}

#pragma mark - 四个button的点击事件

-(void)toButton1{
    
    ButtonDetailsViewController *viewController1=[self.storyboard instantiateViewControllerWithIdentifier:@"ButtonVC"];;
    
    [self.navigationController pushViewController:viewController1 animated:YES];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self segmentAction:nil];
    self.ButtonChoose=1;
    app.splx=@"外卖";
    
}
-(void)toButton2{
    
    ButtonDetailsViewController *viewController2=[self.storyboard instantiateViewControllerWithIdentifier:@"ButtonVC"];
    
    [self.navigationController pushViewController:viewController2 animated:YES];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self segmentAction:nil];
    self.ButtonChoose=2;
    app.splx=@"便利店";
}
-(void)toButton3{
    
    ButtonDetailsViewController *viewController3=[self.storyboard instantiateViewControllerWithIdentifier:@"ButtonVC"];
    
    [self.navigationController pushViewController:viewController3 animated:YES];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self segmentAction:nil];
    self.ButtonChoose=3;
}
-(void)toButton4{
    
    ShopDetailViewController *viewController4=[self.storyboard instantiateViewControllerWithIdentifier:@"DetailsVC"];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self segmentAction:nil];
    [self.navigationController pushViewController:viewController4 animated:YES];
    
    self.ButtonChoose=4;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)PersonalCenter:(id)sender {
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    if ([app._id  isEqual: @""]||app._id == nil) {
        [self performSegueWithIdentifier:@"denglu" sender:nil];
    }else{
        [self performSegueWithIdentifier:@"chenggong" sender:nil];
    }
}
- (IBAction)message:(id)sender {
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    if (app._id == nil||[app._id isEqualToString:@""]) {
    [self performSegueWithIdentifier:@"denglu" sender:nil];
    }else{
        NSString *xx = @"http://www.51anys.com:8080/waimaiwang/user/setRead/";
        NSString *xx1 = [NSString stringWithFormat:@"%@%@",xx,app._id];
        _url=[NSURL URLWithString:xx1];
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_url];
        NSString *postStr=@"";
        [request setHTTPMethod:@"post"];
        NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            ydxiaoxi = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [self performSelectorOnMainThread:@selector(refreshData1:) withObject:ydxiaoxi waitUntilDone:YES];
        }];
        messageViewController *message = [self.storyboard instantiateViewControllerWithIdentifier:@"messageVC"];
        [self.navigationController pushViewController:message animated:YES];
    }
}
@end
